import * as nodeMailer from 'nodemailer';
import { CommonConfig } from '../config';
import { Logger } from '@nestjs/common';

const smtpHost = Buffer.from(
  CommonConfig.ENV.get('MAIL_SMTP'),
  'base64',
).toString();
const smtpPort = CommonConfig.ENV.get('MAIL_PORT');
const mailUser = Buffer.from(
  CommonConfig.ENV.get('MAIL_USER'),
  'base64',
).toString();
const mailPwd = Buffer.from(
  CommonConfig.ENV.get('MAIL_PWD'),
  'base64',
).toString();
const isSsl = CommonConfig.ENV.get('MAIL_SSL') === 'true';

export class Mailer {
  /**
   * @param mailBody
   * @Description 发送邮件
   * {
   *     to: ['123@qq.com', '456@qq.com'] || '123@qq.com,456@qq.com',
   *     subject: '注册验证码',
   *     text: '发送文本时，请传text参数，否则不传',
   *     html: '发送html格式邮件时，请传html参数，否则不传'
   * }
   * @return
   */
  static async emailTo(mailBody: any) {
    // tslint:disable-next-line:max-line-length
    // const transportOptions = {host: smtpHost, port: Number(smtpPort), secure: isSsl, auth: {user: mailUser, pass: mailPwd}, logger: true, debug: false};
    const transportOptions = {
      host: smtpHost, // mail.qq.com
      port: Number(smtpPort), // 25 qq 465
      auth: {
        user: mailUser, // 发送邮件的邮箱地址
        pass: mailPwd, // 邮箱的授权码
      },
      secure: isSsl,
      logger: true,
      debug: false,
      // tls: {
      //     rejectUnauthorized: false,
      // },
    };
    // console.log(transportOptions);
    const transporter = nodeMailer.createTransport(transportOptions);
    const mailOptions = {
      from: mailUser, // 发送者 no-reply@at.live
      to: '', // 接收者，可以同时发送多个(单独发送)，以逗号隔开或使用数组
      cc: '',
      subject: mailBody.subject, // 标题
      text: '',
      html: '',
    };
    if (mailBody.text) {
      mailOptions.text = mailBody.text; // 文本
      delete mailOptions.html;
    }
    if (mailBody.html) {
      mailOptions.html = mailBody.html; // html
      delete mailOptions.text;
    }
    try {
      if (typeof mailBody.to === 'string') {
        mailBody.to = mailBody.to.split(',');
      }
      // console.log(mailOptions);
      mailBody.to.forEach(async (item) => {
        // console.log(item);
        mailOptions.to = item;
        const result = await transporter.sendMail(mailOptions);
        Logger.log(result);
        Logger.log('Message sent successfully!');
        // return result;
      });
      return true;
    } catch (e) {
      Logger.error(e);
      return false;
    } finally {
      transporter.close();
    }
  }
}
